#!/bin/bash

if [ $# -ne 3 ];then
  echo "使用代理  sh proxy.sh ip port all/docker/wget/base(base含yum和ftp等)"
  echo "案例      sh proxy.sh 10.196.51.50 7890 all"
  echo "取消代理  sh proxy.sh cancel proxy all/docker/wget/base(base含yum和ftp等)"
  echo "案例      sh proxy.sh cancel proxy all"
  echo "需另起终端才能看到生效"
  exit
fi

my_proxy=$3
ip=$1
port=$2

proxy_base(){
cat << EOF > /etc/profile.d/proxy.sh
export proxy="http://${ip}:${port}"
export http_proxy=$proxy
export https_proxy=$proxy
export ftp_proxy=$proxy
export no_proxy="localhost, 127.0.0.1, ::1 , 10.*.*.* , 192.168.*.*"
EOF
echo "已设置http_proxy https_proxy ftp_proxy no_proxy地址到/etc/profile.d/proxy.sh，重启也有效"
echo "no_proxy地址为localhost, 127.0.0.1, ::1 , 10.*.*.* , 192.168.*.*"
export proxy="http://${ip}:${port}"
export http_proxy=$proxy
export https_proxy=$proxy
export ftp_proxy=$proxy
export no_proxy="localhost, 127.0.0.1, ::1 , 10.*.*.* , 192.168.*.*"
echo "已设置http_proxy https_proxy ftp_proxy no_proxy地址即刻生效"
}

proxy_docker(){
cat << EOF > /etc/systemd/system/docker.service.d/http-proxy.conf
[Service]
Environment="HTTP_PROXY=http://${ip}:${port}"
Environment="HTTPS_PROXY=http://${ip}:${port}"
EOF
echo "添加docker代理完成"
sudo systemctl daemon-reload
sudo systemctl restart docker
echo "已重启docker使配置生效完成"
}

proxy_wget(){
cat << EOF >> ~/.bash_profile
alias wget='wget -e "http_proxy=http://${ip}:${port}"'
EOF
echo "已添加到~/.bash_profile，重启仍有效"
alias wget='wget -e "http_proxy=http://${ip}:${port}"'
echo "已添加alias wget代理完成，即刻生效"
}

unset_proxy_wget(){
sed -i '/^alias wget/d' ~/.bash_profile
echo "已删除~/.bash_profile下wget的代理内容"
alias wget='wget --no-proxy'
echo "已取消wget alias代理完成"
}


unset_proxy_base(){
unset http_proxy
unset https_proxy
unset ftp_proxy
unset no_proxy
unset proxy
echo "已unset http_proxy https_proxy ftp_proxy no_proxy proxy变量"
rm -rf /etc/profile.d/proxy.sh
echo "已删除/etc/profile.d/proxy.sh基础代理完成"
}

unset_proxy_docker(){
if [ -f /etc/systemd/system/docker.service.d/http-proxy.conf ];then
rm -rf /etc/systemd/system/docker.service.d/http-proxy.conf
echo "已删除docker代理完成"
sudo systemctl daemon-reload
sudo systemctl restart docker
echo "已重启docker完成"
else
echo "无docker代理,无需操作"
fi
}

if [ $1 == "cancel" ] && [ $my_proxy == "all" ];then
unset_proxy_wget
unset_proxy_base
unset_proxy_docker
elif [ $1 == "cancel" ] && [ $my_proxy == "wget" ];then
unset_proxy_wget
elif [ $1 == "cancel" ] &&  $my_proxy == "base" ];then
unset_proxy_base
elif [ $1 == "cancel" ] && [ $my_proxy == "docker" ];then
unset_proxy_docker
elif [ ! $1 == "cancel" ] && [ $my_proxy == "all" ];then
proxy_wget
proxy_base
proxy_docker
elif [ ! $1 == "cancel" ] &&  $my_proxy == "base" ];then
proxy_base
elif [ ! $1 == "cancel" ] && [ $my_proxy == "docker" ];then
proxy_docker
elif [ ! $1 == "cancel" ] && [ $my_proxy == "wget" ];then
proxy_wget
else
echo "命令有误"
fi

